package edu.hubu.commons;

import edu.hubu.exception.InformationNotFoundException;
import edu.hubu.model.Token;
import edu.hubu.model.User;
import edu.hubu.service.impl.TokenService;
import edu.hubu.service.impl.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import net.moon.jpa.service.DefaultService;
import org.slf4j.Logger;

import java.util.Date;

/**
 * @author moonlan
 * @date 2020/10/3 11:15
 */
@SuppressWarnings(value = "all")
public class JwtUils {
    private static final Logger log = org.slf4j.LoggerFactory.getLogger(JwtUils.class);
    private final TokenService tokenService;

    private final UserService service;

    public JwtUils(UserService service, DefaultService<Token, String> tokenService) {
        this.service = service;
        this.tokenService = (TokenService) tokenService;
    }

    public void storeToken(String userId, String token) {
        User byUserName = service.findEntityById(userId);
        Token build = Token.builder().tokenToken(token).tokenExpiryDate(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 15 * 1000)).build();
        build.setUser(byUserName);
        tokenService.addEntity(build);
//        byUserName.setToken(build);
//        service.updateEntityById(byUserName.getUserSid(), byUserName);
    }

    public String getToken(String userId) {
        String token = Jwts.builder().setSubject(userId)
                //有效期15天
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 15 * 1000))
                //采用什么算法是可以自己选择的，不一定非要采用HS512
                .signWith(SignatureAlgorithm.HS256, "oLmRgosdSxz3XOlptCUUvytajh7ybxc1P4c8fBlQMEExr73HSu0olNOA4khWdRm2").compact();
        storeToken(userId, token);
        return "Bearer " + token;
    }


    public void checkToken(String token) {
        if (token == null) {
            throw new IllegalArgumentException("token = null");
        }
        Token tokenToken = tokenService.findByTokenToken(token);
        if (tokenToken == null) {
            log.error("token" + token + "不存在");
            throw new InformationNotFoundException("token" + token + "不存在");
        }

        if (tokenToken.isTokenIsDeleted() || tokenToken.isTokenIsForbidden()) {
            log.error("token" + token + "已无权限");
            throw new InformationNotFoundException("token" + token + "已无权限");
        }

        if (tokenToken.getTokenExpiryDate().before(new Date())) {
            log.error("token" + token + "已过时");
            throw new InformationNotFoundException("token" + token + "已过时");
        }
    }
}
